﻿using Frameworks;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class LoadScence : MonoBehaviour
{
    public Slider slider;

    private void Start()
    {
        Invoke("delayLoadScene", 0.016f);
    }

    private void delayLoadScene()
    {
        StartCoroutine(loadScence());
    }

    private IEnumerator loadScence()
    {
        AsyncOperation asyncOperation = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(GameManager.SceneMgr.CurScene);
        asyncOperation.allowSceneActivation = false;
        int displayProgress = 0;
        while (!asyncOperation.isDone)
        {
            if (asyncOperation.progress >= 0.9f)
            {
                if (displayProgress < 100)
                {
                    displayProgress += 1;
                    Mathf.Clamp(displayProgress, 0, 100);
                    setLoadingPrecentage(displayProgress);
                    yield return new WaitForFixedUpdate();
                }
                else
                {
                    yield return new WaitForFixedUpdate();
                    asyncOperation.allowSceneActivation = true;
                }
            }
            else
            {
                displayProgress = (int)(asyncOperation.progress * 100);
                setLoadingPrecentage(displayProgress);
            }
            //Debug.Log($"{asyncOperation.progress} - {displayProgress}");
            yield return null;
        }
    }

    private void setLoadingPrecentage(int num)
    {
        float x = num / 100f;
        slider.value = x;
    }
}
